import React, { Component } from 'react';
import { connect } from 'dva';
import { Table, Button, Row, Col, Select, Form, Popconfirm, Popover, Input } from 'antd';
import AutomaticModal from './AutomaticModal';

const FormItem = Form.Item;
const Option = Select.Option;

@window.regStateCache
class AutomaticOrder extends Component {

  constructor() {
    super();
    this.state = {
      modalVisible: false,
      visible: false,
      title: '', // modal的title
    };
  }

  handleSubmit(e, page,pageSize) {
    if (e) e.preventDefault();
    const {	automaticPageSize } = this.props;
    this.props.form.validateFieldsAndScroll((err, fieldsValue) => {
      if (err) {return;}
      this.props.dispatch({
        type: 'automatic/queryAutomaticList',
        payload: { ...fieldsValue, 
        	pageIndex: typeof page === 'number' ? page : 1,
        	pageSize: pageSize || automaticPageSize,
        },
      });
    });
  }

  showModal() {
    this.setState({
      modalVisible: true,
      title: '新增',
    });
  }

  updateModal(automaticId) {
    const p = this;
    p.setState({
      modalVisible: true,
      title: '修改',
    }, () => {
      p.props.dispatch({ type: 'automatic/queryUpdateAutomatic', payload: { automaticId } });
    });
  }

  closeModal() {
    this.setState({ modalVisible:false }, () => {
      this.props.dispatch({
        type: 'automatic/saveAutomatic',
        payload: {},
      });
      this._refreshData();
    });
  }


  render() {
    const p = this;
    const { form, automaticList = [],  automaticTotal, automaticPage, automaticPageSize, dispatch, automaticValues={} } = p.props;
    const { getFieldDecorator, resetFields } = form;
    const { title, modalVisible } = p.state;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const columnsList = [
      { title: '主单号', dataIndex: 'autoNo', key: 'autoNo', width: 130, render(text) { return text || '-'; } },
      { title: '任务标题', dataIndex: 'taskTitle', key: 'taskTitle', width: 100, render(text) { return text || '-'; } },
      { title: '商品链接', dataIndex: 'itemUrl', key: 'itemUrl', width: 200, render(text) { return text || '-'; } },
      { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 50, render(text) { return text || '-'; } },
      { title: '商品图片',
      	dataIndex: 'orderPic',
      	key: 'orderPic',
      	width: 75,
      	render(text) {
      		if (!text) return '-';
          const picList = JSON.parse(text).picList;
          const t = picList.length ? picList[0].url : '';
          return (
            t ? <Popover title={null} content={<img role="presentation" src={t} style={{ width: 400 }} />}>
              <img role="presentation" src={t} width={60} height={60} />
            </Popover> : '-'
          );
        }, 
      },
      { title: '账号', dataIndex: 'accountUmber', key: 'accountUmber', width: 150, render(text) { return text || '-'; } },
      { title: '外部订单号', dataIndex: 'orderNumber', key: 'orderNumber', width: 80, render(text) { return text || '-'; } },
      { title: '订单状态',
      	dataIndex: 'status',
      	key: 'status',
      	width: 80,
      	render(text) {
      		switch (text) {
            case 0: return <font color="">新建</font>;
            case 1: return <font color="green">下单成功</font>;
            case 2: return <font color="blue">发货成功</font>;
            case -1: return <font color="red">下单异常</font>;
            default: return '-';
          }
      	}
      },
      { title: '外部订单状态', dataIndex: 'thirdStatus', key: 'thirdStatus', width: 80, render(text) { return text || '-'; } },
      { title: '错误提示', dataIndex: 'errorPrompt', key: 'errorPrompt', width: 110, render(text) { return text || '-'; } },
      { title: '备注', dataIndex: 'detailTitle', key: 'detailTitle', width: 80, render(text) { return text || '-'; } },
      { title: '操作',
        dataIndex: 'operator',
        key: 'operator',
        width: 50,
        render(text, record) {
          return (
            <div>
              <a href="javascript:void(0)" onClick={p.updateModal.bind(p, record.id)}>修改</a>
            </div>);
        },
      },
    ];

    const listPaginationProps = {
      total: automaticTotal,
	    current: automaticPage,
	    pageSize: automaticPageSize,
	    showSizeChanger: true,
	    onChange(pageIndex) {
	       p.handleSubmit(null, pageIndex);
	    },
	    pageSizeOptions: ['20', '50', '100', '200', '500'],
	    onShowSizeChange(current, size) {
	       p.handleSubmit(null, 1, size);
	    },
    };

    return (
      <div>
        <div className="refresh-btn"><Button type="ghost" size="small" onClick={this._refreshData.bind(this)}>刷新</Button></div>
        <Form onSubmit={this.handleSubmit.bind(this)}>
          <Row gutter={20} style={{ width: 800 }}>
            <Col span="8">
              <FormItem
                label="自动下单主单号"
                {...formItemLayout}
              >
                {getFieldDecorator('autoNo', {})(
                  <Input placeholder="请输入主单号" />,
                )}
              </FormItem>
            </Col>
          </Row>
          <Row style={{ marginLeft: 13 }}>
            <Col className="listBtnGroup">
              <Button htmlType="submit" size="large" type="primary">查询</Button>
              <Button size="large" type="ghost" onClick={() => { resetFields(); }}>清空</Button>
            </Col>
          </Row>
        </Form>
        <Row>
          <Col className="operBtn">
          	<Button type="primary" size="large" onClick={p.showModal.bind(p)} >新增自动下单任务</Button>
          </Col>
        </Row>
        <Row>
          <Col>
            <Table
              columns={columnsList}
              dataSource={automaticList}
              bordered
              size="large"
              rowKey={record => record.detailId}
              pagination={listPaginationProps}
              scroll={{ x: 1185 }}
            />
          </Col>
        </Row>
        <AutomaticModal
          visible={modalVisible}
          close={this.closeModal.bind(this)}
          modalValues={automaticValues}
          title={title}
          dispatch={dispatch}
        />
      </div>
    );
  }
}

function mapStateToProps(state) {
  const { automaticList, automaticPage, automaticPageSize, automaticTotal, automaticValues} = state.automatic;
  return {
		automaticList,
    automaticPage,
    automaticPageSize,
    automaticTotal,
    automaticValues,
  };
}

export default connect(mapStateToProps)(Form.create()(AutomaticOrder));
